package code.hkgolden.android.core;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebView;
import android.widget.ProgressBar;
import code.framework.android.core.ApplicationContextHelper;
import code.framework.android.view.ApplicationViewManager;
import code.framework.android.view.ViewHelper;
import code.hkgolden.android.R;
import code.hkgolden.android.data.Reply;
import code.hkgolden.android.data.Topic;
import code.hkgolden.android.service.ContentService;
import code.hkgolden.android.view.NavBarViewHolder;
import code.hkgolden.android.view.ReplyViewHolder;
import code.hkgolden.android.view.TopicViewHolder;

import com.google.inject.Inject;

public class HkgoldenViewManager extends ApplicationViewManager {

	@Inject
	ContentService contentService;

	@Override
	protected void setResourceLayoutClass() {
		super.resourceLayoutClass = code.hkgolden.android.R.layout.class;
	}

	@Override
	protected void setResourceIdClass() {
		super.resourceIdClass = code.hkgolden.android.R.id.class;
	}

	public NavBarViewHolder createNavBarViewHolder(Activity activity,
			String title) {
		activity.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.nav_bar);
		final NavBarViewHolder holder = new NavBarViewHolder();
		super.reflect(activity, holder);
		holder.leftButton.setVisibility(View.GONE);
		holder.rightButton.setVisibility(View.GONE);
		holder.title.setText(title);
		return holder;
	}

	public HkgoldenTaskManager.ProgressHandler createProgressHandler(
			Activity activity) {
		// ProgressBar progressBar = (ProgressBar) activity
		// .findViewById(R.id.progressBar);
		ProgressBar progressBar = (ProgressBar) super.getLayoutInflater(
				activity).inflate(R.layout.progress_bar, null);
		activity.getWindow().addContentView(
				progressBar,
				new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
						ViewGroup.LayoutParams.WRAP_CONTENT));
		HkgoldenTaskManager.ProgressHandler progressHandler = new HkgoldenTaskManager.ProgressHandler(
				progressBar);
		return progressHandler;
	}

	public TopicViewHolder createTopicBriefViewHolder(ViewGroup parent,
			Context context) {
		final TopicViewHolder holder = new TopicViewHolder();
		holder.container = (ViewGroup) getLayoutInflater(context).inflate(
				R.layout.topic_brief, parent, false);
		holder.container.setTag(holder);
		super.reflect((ViewGroup) holder.container, holder);
		return holder;
	}

	public TopicViewHolder createTopicViewHolder(ViewGroup parent,
			Context context) {
		final TopicViewHolder holder = new TopicViewHolder();
		holder.container = (ViewGroup) getLayoutInflater(context).inflate(
				R.layout.topic, parent, false);
		holder.container.setTag(holder);
		super.reflect((ViewGroup) holder.container, holder);
		return holder;
	}

	public ReplyViewHolder createReplyViewHolder(ViewGroup parent,
			Context context) {
		final ReplyViewHolder holder = new ReplyViewHolder();
		holder.container = (ViewGroup) getLayoutInflater(context).inflate(
				R.layout.reply, parent, false);
		holder.container.setTag(holder);
		super.reflect((ViewGroup) holder.container, holder);
		return holder;
	}

	public void renderSelectTopic(WebView webView, Context context)
			throws IOException {
		final StringBuilder html = new StringBuilder(200);
		html.append("<html><style><!--");
		final byte[] bytes = ApplicationContextHelper.getAssetAsBytes(
				"app.css", context);
		html.append(new String(bytes));
		html.append("--></style>");
		html.append("<div id=\"selection\"");
		Map<String, String> channelMap = contentService.channels(context);
		for (String key : channelMap.keySet()) {
			if (key.length() > 0) {
				html.append("<a href=\"?ch=").append(key).append("\">").append(
						channelMap.get(key)).append("</a>");
			}
		}
		html.append("</div>");
		html.append("</html>");
		logger.trace("html = {}", html);
		ViewHelper.loadWebView(null, html.toString(), webView);
	}

	public void renderSelectPage(int maxPage, WebView webView, Context context)
			throws IOException {
		final StringBuilder html = new StringBuilder(200);
		html.append("<html><style><!--");
		final byte[] bytes = ApplicationContextHelper.getAssetAsBytes(
				"app.css", context);
		html.append(new String(bytes));
		html.append("--></style>");
		html.append("<div id=\"selection\"");
		for (int i = 1; i <= maxPage; i++) {
			html.append("<a href=\"?p=").append(i).append("\">第").append(i)
					.append("頁</a>");
		}
		html.append("</div>");
		html.append("</html>");
		logger.trace("html = {}", html);
		ViewHelper.loadWebView(null, html.toString(), webView);
	}

	public void renderTopicViewHolder(Topic topic,
			TopicViewHolder topicViewHolder) {
		topicViewHolder.title.setText(topic.getTitle());
		topicViewHolder.author.setText(topic.getAuthorName());
		topicViewHolder.replies.setText("(" + topic.getRepliesCount() + "回覆)");
		if (topic.getReplies() == null) {
			if (topic.getRating() != null) {
				// final double rating = ((double) topic.getRatingGood()
				// / (double) topic.getRatingBad() + (double) topic
				// .getRatingGood());
				final DecimalFormat df = new DecimalFormat("#.#");
				if (topic.getRating() != 0.0) {
					topicViewHolder.rating
							.setText(df.format(topic.getRating()));
				}
			}
			// logger.warn("return");
			return;
		}
		/*
		 * FIXME: workaround
		 */
		// holder.body.setBackgroundResource(R.drawable.background);
		topicViewHolder.body.setBackgroundColor(0);
		loadWebView(topic.getBody(), topicViewHolder.body);
	}

	public void renderReplyViewHolder(Reply reply,
			ReplyViewHolder replyViewHolder) {
		replyViewHolder.author.setText(reply.getAuthorName());
		/*
		 * FIXME: workaround
		 */
		// holder.body.setBackgroundResource(R.drawable.background);
		replyViewHolder.body.setBackgroundColor(0);
		loadWebView(reply.getBody(), replyViewHolder.body);
		replyViewHolder.body.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
	}

	protected void loadWebView(String data, WebView webView) {
		// logger.trace("before = {}", data);
		data = data.replace("img src=\"/faces/",
				"img src=\"file:///android_asset/faces/");
		// logger.trace("after = {}", data);
		ViewHelper.loadWebView(null,
				"<style>* {color: #333333;}blockquote {margin:0 0 0 0}</style>"
						+ data, webView);
	}

}
